﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;


namespace HosPlat.API
{
    public class CommonClass
    {
        //private const string method = "GET";
        //private const string appcode = "2f3d8030c66c4fb6b55bcd26eda99558";

        #region web服务请求 get post
        public static string Get(string url)
        {
            HttpWebRequest request = WebRequest.Create(url) as System.Net.HttpWebRequest;
            request.Method = "GET";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)";
            HttpWebResponse result = request.GetResponse() as HttpWebResponse;
            StreamReader sr = new StreamReader(result.GetResponseStream(), Encoding.UTF8);
            string strResult = sr.ReadToEnd();
            sr.Close();
            return strResult;
        }

        public static string Post(string url, System.Collections.Specialized.NameValueCollection para)
        {
            try
            {
                WebClient WebClientObj = new WebClient();

                byte[] byRemoteInfo = WebClientObj.UploadValues(url, "POST", para);//请求地址,传参方式,参数集合

                string rtContent = Encoding.UTF8.GetString(byRemoteInfo);//获取返回值 
                return rtContent;
            }
            catch (Exception)
            {
                return "";
            }
        }
        #endregion

        #region MD5
        public static string Md5(string source)
        {
            if (string.IsNullOrEmpty(source))
                return string.Empty;

            string result = string.Empty;
            System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(source));

            result = BitConverter.ToString(s).Replace("-", string.Empty);
            return result.ToLower();

        }
        #endregion

        #region DataTable根据条件过滤表
        /// <summary>   
        /// 根据条件过滤表   
        /// </summary>   
        /// <param name="dt">未过滤之前的表</param>   
        /// <param name="filter">过滤条件</param>   
        /// <returns>返回过滤后的表</returns>   
        public static DataTable FilterTable(DataTable dt, string filter)
        {
            DataTable newTable = dt.Clone();
            DataRow[] drs = dt.Select(filter);
            foreach (DataRow dr in drs)
            {
                newTable.Rows.Add(dr.ItemArray);
            }
            return newTable;
        }
        #endregion

        #region 数据表转换为list，泛型
        public static List<T> GetTableToList<T>(DataTable table)
        {
            List<T> list = new List<T>();
            T t = default(T);
            PropertyInfo[] propertypes = null;
            string tempName = string.Empty;
            foreach (DataRow row in table.Rows)
            {
                t = Activator.CreateInstance<T>();
                propertypes = t.GetType().GetProperties();
                foreach (PropertyInfo pro in propertypes)
                {
                    tempName = pro.Name;
                    if (table.Columns.Contains(tempName))
                    {
                        object value = row[tempName];
                        if (!value.ToString().Equals(""))
                        {
                            pro.SetValue(t, value, null);
                        }
                    }
                }
                list.Add(t);
            }
            return list;
        }
        #endregion

        #region 身份证验证
        /// <summary>  
        /// 验证身份证合理性  
        /// </summary>  
        /// <param name="Id"></param>  
        /// <returns></returns>  
        public static bool CheckIDCard(string idNumber)
        {
            if (idNumber.Length == 18)
            {
                bool check = CheckIDCard18(idNumber);
                return check;
            }
            else if (idNumber.Length == 15)
            {
                bool check = CheckIDCard15(idNumber);
                return check;
            }
            else
            {
                return false;
            }
        }


        /// <summary>  
        /// 18位身份证号码验证  
        /// </summary>  
        private static bool CheckIDCard18(string idNumber)
        {
            long n = 0;
            if (long.TryParse(idNumber.Remove(17), out n) == false
                || n < Math.Pow(10, 16) || long.TryParse(idNumber.Replace('x', '0').Replace('X', '0'), out n) == false)
            {
                return false;//数字验证  
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(idNumber.Remove(2)) == -1)
            {
                return false;//省份验证  
            }
            string birth = idNumber.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证  
            }
            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            char[] Ai = idNumber.Remove(17).ToCharArray();
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
            }
            int y = -1;
            Math.DivRem(sum, 11, out y);
            if (arrVarifyCode[y] != idNumber.Substring(17, 1).ToLower())
            {
                return false;//校验码验证  
            }
            return true;//符合GB11643-1999标准  
        }


        /// <summary>  
        /// 16位身份证号码验证  
        /// </summary>  
        private static bool CheckIDCard15(string idNumber)
        {
            long n = 0;
            if (long.TryParse(idNumber, out n) == false || n < Math.Pow(10, 14))
            {
                return false;//数字验证  
            }
            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
            if (address.IndexOf(idNumber.Remove(2)) == -1)
            {
                return false;//省份验证  
            }
            string birth = idNumber.Substring(6, 6).Insert(4, "-").Insert(2, "-");
            DateTime time = new DateTime();
            if (DateTime.TryParse(birth, out time) == false)
            {
                return false;//生日验证  
            }
            return true;
        }

        #endregion

        #region 生成图片验证码
        /// <summary>
        /// 创建验证码的图片,输出流
        /// </summary>
        /// <param name="containsPage">要输出到的page对象</param>
        /// <param name="validateNum">验证码</param>
        public static byte[] CreateValidateGraphic(string validateCode)
        {
            Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);
            Graphics g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器
                Random random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的干扰线
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }
                Font font = new Font("Arial", 12, (FontStyle.Bold | FontStyle.Italic));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
                 Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(validateCode, font, brush, 3, 2);
                //画图片的前景干扰点
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                //保存图片数据
                MemoryStream stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                //输出图片流
                return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
        #endregion

        #region 生成随机数
        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <param name="VcodeNum">位数</param>
        /// <returns></returns>
        public static string RndNum(int VcodeNum)
        {
            string Vchar = "0,1,2,3,4,5,6,7,8,9";
            string[] VcArray = Vchar.Split(",".ToCharArray());
            string VNum = "";
            System.Random ro = new Random();
            for (int i = 1; i <= VcodeNum; i++)
            {
                int decA = ro.Next(0, 10);
                VNum = VNum + VcArray[decA];
            }

            return VNum;
        }
        #endregion

        #region 去除HTML标记
        /// <summary>
        /// 去除HTML标记
        /// </summary>
        /// <param name="Htmlstring">字符串</param>
        /// <returns>过滤后的串</returns>
        public static string NoHTML(string _html) //去除HTML标记
        {
            //删除脚本
            _html = Regex.Replace(_html, @"(?i)font-[^\-]+:((?!pt|;).)+(pt|;)?", "");
            return _html;
        }

        /// <summary>
        /// 去除HTML标记,如果对象为null,返回"0"
        /// </summary>
        /// <param name="Htmlstring">对象</param>
        /// <returns>过滤后的串</returns>
        public static string NoHTML1(object Htmlstring) //去除HTML标记
        {
            if (Htmlstring == null)
            {
                return "0";
            }
            return NoHTML(Htmlstring.ToString());
        }
        #endregion

        #region 获取访问者ip
        public static string GetIP()
        {
            string result = String.Empty;
            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (result != null && result != String.Empty)
            {
                //可能有代理
                if (result.IndexOf(".") == -1)    //没有“.”肯定是非IPv4格式
                    result = null;
                else
                {
                    if (result.IndexOf(",") != -1)
                    {
                        //有“,”，估计多个代理。取第一个不是内网的IP。
                        result = result.Replace(" ", "").Replace("'", "");
                        string[] temparyip = result.Split(",;".ToCharArray());
                        for (int i = 0; i < temparyip.Length; i++)
                        {
                            if (IsIPAddress(temparyip[i])
                                && temparyip[i].Substring(0, 3) != "10."
                                && temparyip[i].Substring(0, 7) != "192.168"
                                && temparyip[i].Substring(0, 7) != "172.16.")
                            {
                                return temparyip[i];    //找到不是内网的地址
                            }
                        }
                    }
                    else if (IsIPAddress(result)) //代理即是IP格式 ,IsIPAddress判断是否是IP的方法,
                        return result;
                    else
                        result = null;    //代理中的内容 非IP，取IP
                }

            }

            string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (null == result || result == String.Empty)
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (result == null || result == String.Empty)
                result = HttpContext.Current.Request.UserHostAddress;

            return result;

        }
        private static bool IsIPAddress(string str1)
        {
            if (str1 == null || str1 == string.Empty || str1.Length < 7 || str1.Length > 15) return false;

            string regformat = @"^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$";

            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }
        public static string GetIPNum()
        {
            return GetIPNum(GetIP());
        }
        public static string GetIPNum(string ip)
        {
            long num = 0;
            if (!string.IsNullOrEmpty(ip))
            {
                string[] ips = ip.Split('.');
                if (ips.Length == 4)
                {
                    long num1 = long.Parse(ips[0]) * 256 * 256 * 256;
                    long num2 = long.Parse(ips[1]) * 256 * 256;
                    long num3 = long.Parse(ips[2]) * 256;
                    long num4 = long.Parse(ips[3]);
                    num = num1 + num2 + num3 + num4;
                }
            }
            return num.ToString();
        }

        #endregion

        #region 发送邮件
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="fromAddress">发信邮箱账号</param>
        /// <param name="fromAddressPwd">发信邮箱账号密码</param>
        /// <param name="toAddress">收信邮箱地址</param>
        /// <param name="title">邮件标题</param>
        /// <param name="content">邮件内容</param>
        /// <returns></returns>
        public static bool SendMail(string fromAddress, string fromAddressPwd, string toAddress, string title, string content)
        {
            MailAddress to = new MailAddress(toAddress);//接收者邮箱
            MailAddress from = new MailAddress(fromAddress);//发送者邮箱
            MailMessage mail = new MailMessage(from, to);
            mail.Subject = title;
            mail.IsBodyHtml = true;
            mail.Body = content;
            SmtpClient client = new SmtpClient();
            client.Host = "smtp.exmail.qq.com";//设置发送者邮箱对应的smtpserver
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(fromAddress, fromAddressPwd);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            try
            {
                client.Send(mail);
                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="fromAddress">发信邮箱账号</param>
        /// <param name="fromAddressPwd">发信邮箱账号密码</param>
        /// <param name="toAddress">收信邮箱地址</param>
        /// <param name="title">邮件标题</param>
        /// <param name="content">邮件内容</param>
        /// <returns></returns>
        public static bool SendMail(string toAddress, string title, string content)
        {
            string fromAddress = "yfzsb@zhenshiyuan.com";
            string fromAddressPwd = "jiubugaosuNI2015";
            MailAddress to = new MailAddress(toAddress);//接收者邮箱
            MailAddress from = new MailAddress(fromAddress);//发送者邮箱
            MailMessage mail = new MailMessage(from, to);
            mail.Subject = title;
            mail.IsBodyHtml = true;
            mail.Body = content;
            SmtpClient client = new SmtpClient();
            client.Host = "smtp.exmail.qq.com";//设置发送者邮箱对应的smtpserver
            client.UseDefaultCredentials = false;
            client.Credentials = new NetworkCredential(fromAddress, fromAddressPwd);
            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            try
            {
                client.Send(mail);
                return true;
            }
            catch (Exception)
            {
                return false;
            }

        }

        #endregion

        #region discuz论坛cookie解析
        public static string GetUserName(HttpContextBase httpContextBase, string cookieName)
        {
            string str = "";
            if (httpContextBase != null)
            {
                if (httpContextBase.Request.Cookies[cookieName] != null)
                {
                    HttpCookie hc = httpContextBase.Request.Cookies[cookieName];
                }
            }
            return str;
        }
        #endregion

        #region 浏览器型号

        /// <summary>
        /// 获取访问者浏览器
        /// </summary>
        /// <param name="agent"></param>
        /// <returns></returns>
        public static int GetSoft(string agent)
        {
            int soft = 0;
            if (agent.Contains("NetCaptor"))
            {
                soft = 1;
            }
            else if (agent.Contains("Firefox"))
            {
                soft = 2;
            }
            else if (agent.Contains("Opera"))
            {
                soft = 3;
            }
            else if (agent.Contains("Safari"))
            {
                soft = 4;
            }
            else if (agent.Contains("Chrome"))
            {
                soft = 5;
            }
            else if (agent.Contains("MSIE 6"))
            {
                soft = 6;
            }
            else if (agent.Contains("MSIE 7"))
            {
                soft = 7;
            }
            else if (agent.Contains("MSIE 8"))
            {
                soft = 8;
            }
            else if (agent.Contains("MSIE 9"))
            {
                soft = 9;
            }
            else if (agent.Contains("MSIE 10"))
            {
                soft = 10;
            }
            else if (agent.Contains("MSIE 11"))
            {
                soft = 11;
            }
            return soft;
        }

        #endregion

        #region 系统型号

        /// <summary>
        /// 获取浏览者系统
        /// </summary>
        /// <param name="agent"></param>
        /// <returns></returns>
        public static int GetOS(string agent)
        {
            int os = 0;
            if (agent.Contains("Windows NT 5.0"))
            {
                os = 1;
            }
            else if (agent.Contains("Windows NT 5.1"))
            {
                os = 2;
            }
            else if (agent.Contains("Windows NT 6.1"))
            {
                os = 3;
            }
            else if (agent.Contains("unix") || agent.Contains("linux") || agent.Contains("SunOS") || agent.Contains("BSD"))
            {
                os = 4;
            }
            else if (agent.Contains("Mac"))
            {
                os = 5;
            }
            return os;
        }
        #endregion

        #region 异步post页面
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pageUrl">请求页面</param>
        /// <returns>json格式数据</returns>
        public static string GetResponseData(string pageUrl)
        {
            return GetResponseData(pageUrl, new Dictionary<string, string>());
        }
        #endregion

        #region 异步post页面
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pageUrl">请求页面</param>
        /// <returns>json格式数据</returns>
        public static string GetResponseData(string pageUrl, Dictionary<string, string> dic)
        {
            string strResult = "";
            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(pageUrl);
                // myRequest.Referer = "http://www.cooju.cn/";
                foreach (string item in dic.Keys)
                {
                    myRequest.Headers.Add(item, dic[item]);
                }
                myRequest.Method = "POST";
                myRequest.ContentType = "application/x-www-form-urlencoded";
                try
                {
                    HttpWebResponse HttpWResp = (HttpWebResponse)myRequest.GetResponse();
                    Stream myStream = HttpWResp.GetResponseStream();
                    StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
                    StringBuilder strBuilder = new StringBuilder();
                    while (-1 != sr.Peek())
                    {
                        strBuilder.Append(sr.ReadLine());
                    }
                    strResult = strBuilder.ToString();
                }
                catch (Exception exp)
                {
                    strResult = "{\"error\":\"false\",\"error_description\":\"" + exp.Message + "\"}";
                }
            }
            catch (Exception exp)
            {
                strResult = "{\"error\":\"false\",\"error_description\":\"" + exp.Message + "\"}";
            }
            return strResult;
        }
        #endregion

        #region 获取页面内容
        public static string GetUrlContent(string uri, string method, Dictionary<string, string> headers)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
            request.Method = method;
            if (headers != null)
            {
                foreach (KeyValuePair<string, string> headersKey in headers)
                {
                    request.Headers.Add(headersKey.Key, headersKey.Value);
                }
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
            string respHtml;
            try
            {
                respHtml = reader.ReadToEnd();
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                reader.Close();
            }
            return respHtml;

        }
        #endregion

        #region 获取页面内容

        public static string GetUrlContent(string url)
        {
            return GetUrlContent(url, new Dictionary<string, string>());
        }
        public static string GetUrlContent(string url, Dictionary<string, string> dic)
        {
            WebClient wc = new WebClient();
            wc.Credentials = CredentialCache.DefaultCredentials;
            wc.Encoding = Encoding.UTF8;

            foreach (KeyValuePair<string, string> item in dic)
            {
                wc.Headers.Add(item.Key, item.Value);
            }
            string returnText = wc.DownloadString(url);
            return returnText;
        }
        #endregion

        #region 异步post页面，json参数
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Url">请求页面</param>
        /// <param name="JSONData">请求json参数</param>
        /// <returns>json格式数据</returns>
        public static string GetResponseData(string JSONData, string Url)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(JSONData);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentLength = bytes.Length;
            request.ContentType = "text/xml";
            // request.Referer = "http://www.cooju.cn/";
            Stream reqstream = request.GetRequestStream();
            reqstream.Write(bytes, 0, bytes.Length);

            //声明一个HttpWebRequest请求  
            request.Timeout = 90000;
            //设置连接超时时间  
            request.Headers.Set("Pragma", "no-cache");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream streamReceive = response.GetResponseStream();
            Encoding encoding = Encoding.UTF8;

            StreamReader streamReader = new StreamReader(streamReceive, encoding);
            string strResult = streamReader.ReadToEnd();
            streamReceive.Dispose();
            streamReader.Dispose();

            return strResult;
        }
        #endregion

        #region 判断是否手机访问
        public static bool IsMobile(string agent)
        {
            bool result = false;
            string sUserAgent = agent.ToLower();

            if (sUserAgent.Contains("ipad") || sUserAgent.Contains("iphone") || sUserAgent.Contains("midp") || sUserAgent.Contains("rv:1.2.3.4") || sUserAgent.Contains("ucweb") || sUserAgent.Contains("android") || sUserAgent.Contains("windows ce") || sUserAgent.Contains("windows mobile"))
            {
                result = true;
            }
            return result;
        }
        #endregion


        #region 获取资料添加时间为多久前
        public static string GetTimeGo(string createtime)
        {
            DateTime create = Convert.ToDateTime(createtime);
            DateTime Now = DateTime.Now;
            TimeSpan ts = Now - create;
            string str = "";
            var days = ts.Days;
            if (days > 0)
            {
                str = days + "天前";
            }
            else
            {
                var hour = ts.Hours;
                if (hour > 0)
                {
                    str = hour + "小时前";
                }
                else
                {
                    var Minute = ts.Minutes;
                    if (Minute > 0)
                    {
                        str = Minute + "分钟前";
                    }
                    else
                    {
                        var secend = ts.Seconds;
                        if (secend > 0)
                        {
                            str = secend + "秒前";
                        }
                    }
                }
            }
            return str;
        }
        #endregion

        #region 截取字符串
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="str">源字符串</param>
        /// <param name="length">截取长度</param>
        /// <param name="type">0加…… 1不加</param>
        /// <returns></returns>
        public static string GetSubstring(string str, int length, int type)
        {
            string returnStr = "";
            if (!string.IsNullOrEmpty(str))
            {

                if (str.Length >= length)
                {
                    returnStr = str.Substring(0, length);
                    if (type == 0)
                    {
                        returnStr += "……";
                    }
                }
                else
                {
                    returnStr = str;
                }
            }
            return returnStr;

        }
        #endregion

        #region 写txt日志文件
        public static void WriteLog(string type, string className, string content)
        {
            try
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + "LOG";
                if (!Directory.Exists(path))//如果日志目录不存在就创建
                {
                    Directory.CreateDirectory(path);
                }

                string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");//获取当前系统时间
                string filename = path + "/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";//用日期对日志文件命名

                //创建或打开日志文件，向日志文件末尾追加记录
                StreamWriter mySw = File.AppendText(filename);

                //向日志文件写入内容
                string write_content = "=========================================================\r\n" + time + "\r\n" + type + " " + className + "\r\n" + content;
                mySw.WriteLine(write_content);

                //关闭日志文件
                mySw.Close();
            }
            catch (Exception ex)
            {
                string ss = ex.Message;
            }

        }
        #endregion

        #region 数字转英文字母
        /// <summary>
        /// 获取大写英文字母
        /// </summary>
        /// <param name="i"></param>
        /// <returns></returns>
        public static string GetEnglish(int i)
        {
            string str = "ABCDEFGHIGKLMNOPQRSTUVWXYZ";
            return str.Substring(i - 1, 1);
        }
        #endregion

        #region 访问浏览器下载并保存文件
        public static void SaveWebFile(string url, string fileType, string saveFilePath, string saveFileName)
        {
            WebClient wc = new WebClient();
            string path = HttpContext.Current.Server.MapPath(saveFilePath);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            wc.DownloadFile(url, path + saveFileName);

        }
        #endregion

        #region 流下载
        public static void DownLoadFile(HttpContextBase page, string filename)
        {
            string filepath = page.Server.MapPath(filename);
            string fileExt = Path.GetExtension(filepath);
            string savefilename = DateTime.Now.ToString("yyyyMMddHHmmss");

            FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();

            page.Response.Clear();
            page.Response.Charset = "UTF-8";
            string str = "text/html";
            switch (fileExt.Substring(1).ToLower())
            {
                #region 文件头对应的页面格式

                case "doc": str = "application/msword"; break;
                case "pdf": str = "application/pdf"; break;
                case "zip": str = "application/zip"; break;
                case "xls": str = "application/vnd.ms-excel"; break;
                case "xml": str = "text/xml"; break;
                case "mpeg": str = "video/mpeg"; break;
                case "mpg": str = "video/mpeg"; break;
                case "gif": str = "image/gif"; break;
                case "jpeg": str = "image/jpeg"; break;
                case "jpg": str = "image/jpeg"; break;
                case "jpe": str = "image/jpeg"; break;
                case "txt": str = "text/plain"; break;
                case "html": str = "text/html"; break;
                case "png": str = "image/png"; break;
                    //                case "ez":str= "application/andrew-inset";break;
                    //case "hqx" : str= "application/mac-binhex40";break; 
                    //case "cpt" : str= "application/mac-compactpro";break; 
                    //case "bin" : str= "application/octet-stream";break; 
                    //case "dms" : str= "application/octet-stream";break; 
                    //case "lha" : str= "application/octet-stream";break;
                    //case "ief": str = "image/ief"; break;
                    //case "lzh": str = "application/octet-stream"; break; 
                    //case "exe" : str= "application/octet-stream";break; 
                    //case "class" : str= "application/octet-stream";break; 
                    //case "so" : str= "application/octet-stream";break; 
                    //case "dll" : str= "application/octet-stream";break; 
                    //case "oda" : str= "application/oda";break; 
                    //case "ai" : str= "application/postscript";break; 
                    //case "eps" : str= "application/postscript";break; 
                    //case "ps" : str= "application/postscript";break; 
                    //case "smi" : str= "application/smil";break; 
                    //case "smil" : str= "application/smil";break; 
                    //case "mif" : str= "application/vnd.mif";break; 
                    //case "ppt" : str= "application/vnd.ms-powerpoint";break; 
                    //case "wbxml" : str= "application/vnd.wap.wbxml";break; 
                    //case "wmlc" : str= "application/vnd.wap.wmlc";break; 
                    //case "wmlsc" : str= "application/vnd.wap.wmlscriptc";break; 
                    //case "bcpio" : str= "application/x-bcpio";break; 
                    //case "vcd" : str= "application/x-cdlink";break; 
                    //case "pgn" : str= "application/x-chess-pgn";break; 
                    //case "cpio" : str= "application/x-cpio";break; 
                    //case "csh" : str= "application/x-csh";break; 
                    //case "dcr" : str= "application/x-director";break; 
                    //case "dir" : str= "application/x-director";break; 
                    //case "dxr" : str= "application/x-director";break; 
                    //case "dvi" : str= "application/x-dvi";break; 
                    //case "spl" : str= "application/x-futuresplash";break; 
                    //case "gtar" : str= "application/x-gtar";break; 
                    //case "hdf" : str= "application/x-hdf";break; 
                    //case "js" : str= "application/x-javascript";break; 
                    //case "skp" : str= "application/x-koan";break; 
                    //case "skd" : str= "application/x-koan";break; 
                    //case "skt": str="application/x-koan";break; 
                    //case "skm": str= "application/x-koan";break; 
                    //case "latex": str= "application/x-latex";break; 
                    //case "nc": str= "application/x-netcdf";break; 
                    //case "cdf": str= "application/x-netcdf";break; 
                    //case "sh": str= "application/x-sh";break; 
                    //case "shar": str= "application/x-shar";break; 
                    //case "swf": str= "application/x-shockwave-flash";break; 
                    //case "sit": str= "application/x-stuffit";break; 
                    //case "sv4cpio": str= "application/x-sv4cpio";break; 
                    //case "sv4crc": str= "application/x-sv4crc";break; 
                    //case "tar": str= "application/x-tar";break; 
                    //case "tcl": str= "application/x-tcl";break; 
                    //case "tex": str= "application/x-tex";break; 
                    //case "texinfo": str= "application/x-texinfo";break; 
                    //case "texi": str= "application/x-texinfo";break; 
                    //case "t": str= "application/x-troff";break; 
                    //case "tr": str= "application/x-troff";break; 
                    //case "roff": str= "application/x-troff";break; 
                    //case "man": str= "application/x-troff-man";break; 
                    //case "me": str= "application/x-troff-me";break; 
                    //case "ms": str= "application/x-troff-ms";break; 
                    //case "ustar": str= "application/x-ustar";break; 
                    //case "src": str= "application/x-wais-source";break; 
                    //case "xhtml": str= "application/xhtml+xml";break; 
                    //case "xht": str= "application/xhtml+xml";break; 
                    //case "au": str= "audio/basic";break; 
                    //case "snd": str= "audio/basic";break; 
                    //case "mid": str= "audio/midi";break; 
                    //case "midi": str= "audio/midi";break; 
                    //case "kar": str= "audio/midi";break; 
                    //case "mpga": str= "audio/mpeg";break; 
                    //case "mp2": str= "audio/mpeg";break; 
                    //case "mp3": str= "audio/mpeg";break; 
                    //case "aif": str= "audio/x-aiff";break; 
                    //case "aiff": str= "audio/x-aiff";break; 
                    //case "aifc": str= "audio/x-aiff";break; 
                    //case "m3u": str= "audio/x-mpegurl";break; 
                    //case "ram": str= "audio/x-pn-realaudio";break; 
                    //case "rm": str= "audio/x-pn-realaudio";break; 
                    //case "rpm": str= "audio/x-pn-realaudio-plugin";break; 
                    //case "ra": str= "audio/x-realaudio";break; 
                    //case "wav": str= "audio/x-wav";break; 
                    //case "pdb": str= "chemical/x-pdb";break; 
                    //case "xyz": str= "chemical/x-xyz";break; 
                    //case "bmp": str= "image/bmp";break; 
                    //case "tiff": str= "image/tiff";break; 
                    //case "tif": str= "image/tiff";break; 
                    //case "djvu": str= "image/vnd.djvu";break; 
                    //case "djv": str= "image/vnd.djvu";break; 
                    //case "wbmp": str= "image/vnd.wap.wbmp";break; 
                    //case "ras": str= "image/x-cmu-raster";break; 
                    //case "pnm": str= "image/x-portable-anymap";break; 
                    //case "pbm": str= "image/x-portable-bitmap";break; 
                    //case "pgm": str= "image/x-portable-graymap";break; 
                    //case "ppm": str= "image/x-portable-pixmap";break; 
                    //case "rgb": str= "image/x-rgb";break; 
                    //case "xbm": str= "image/x-xbitmap";break; 
                    //case "xpm": str= "image/x-xpixmap";break; 
                    //case "xwd": str= "image/x-xwindowdump";break; 
                    //case "igs": str= "model/iges";break; 
                    //case "iges": str= "model/iges";break; 
                    //case "msh": str= "model/mesh";break; 
                    //case "mesh": str= "model/mesh";break; 
                    //case "silo": str= "model/mesh";break; 
                    //case "wrl": str= "model/vrml";break; 
                    //case "vrml": str= "model/vrml";break; 
                    //case "css": str= "text/css";break; 
                    //case "htm": str= "text/html";break; 
                    //case "asc": str= "text/plain";break; 
                    //case "rtx": str= "text/richtext";break; 
                    //case "rtf": str= "text/rtf";break; 
                    //case "sgml": str= "text/sgml";break; 
                    //case "sgm": str= "text/sgml";break; 
                    //case "tsv": str= "text/tab-separated-values";break; 
                    //case "wml": str= "text/vnd.wap.wml";break; 
                    //case "wmls": str= "text/vnd.wap.wmlscript";break; 
                    //case "etx": str= "text/x-setext";break; 
                    //case "xsl": str= "text/xml";break; 
                    //case "mpe": str= "video/mpeg";break; 
                    //case "qt": str= "video/quicktime";break; 
                    //case "mov": str= "video/quicktime";break; 
                    //case "mxu": str= "video/vnd.mpegurl";break; 
                    //case "avi": str= "video/x-msvideo";break;
                    //case "movie": str = "video/x-sgi-movie"; break;
                    //case "ice": str = "x-conference/x-cooltalk"; break;
                    #endregion
            }

            page.Response.ContentType = str;
            page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(savefilename + fileExt, System.Text.Encoding.UTF8));
            page.Response.BinaryWrite(bytes);
            page.Response.End();
            page.Response.Flush();

        }
        #endregion

        #region 导出excel

        public static string WriteExcel(DataTable ds, string path, string filename)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            StreamWriter sw = new StreamWriter(path + filename, false, Encoding.UTF8);
            try
            {

                StringBuilder strLine = new StringBuilder();
                for (int i = 0; i < ds.Columns.Count; i++)
                {
                    strLine.Append(ds.Columns[i].ColumnName.ToString() + Convert.ToChar(9));
                }
                strLine.Append(Environment.NewLine);
                for (int i = 0; i < ds.Rows.Count; i++)
                {
                    for (int j = 0; j < ds.Columns.Count; j++)
                    {
                        strLine.Append(ds.Rows[i][j].ToString() + "\t");
                    }
                    strLine.Append(Environment.NewLine);
                }
                sw.Write(strLine.ToString());
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                sw.Flush();
                sw.Close();
            }
        }

        public static void ExportDsToXls(HttpContextBase page, string fileName, string html)
        {

            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            page.Response.Clear();
            page.Response.Charset = "gb2312";
            page.Response.ContentType = "application/vnd.ms-excel";
            page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName) + ".xls");
            page.Response.Write("<html><head><META http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\"></head><body>");

            page.Response.Write(html);

            page.Response.Write(tw.ToString());
            page.Response.Write("</body></html>");
            page.Response.End();
            hw.Close();
            hw.Flush();
            tw.Close();
            tw.Flush();
        }
        #endregion


    }
}
